﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NetJavap.JVM;

namespace NetJavap.ConstantInfos
{
    public class ConstantMethodRefInfo : ConstantMemberInfo, IWithMethodDescriptorMember
    {
        private MethodInfo _targetMethod;

        private TypeInfo _returnType;
        private TypeInfo[] _parameters;

        public ConstantUtf8Info Descriptor
        {
            get { return base.NameAndKeyInfo.Descriptor; }
        }

        public TypeInfo ReturnType
        {
            get
            {
                if (this._returnType == null)
                {
                    this.Init();
                }
                return this._returnType;
            }
        }

        public TypeInfo[] Parameters
        {
            get {
                if (this._parameters == null)
                {
                    this.Init();
                }
                return this._parameters;
            }
        }

        private void Init()
        {
            ArrayBuilder.AnalyseDescriptor(this.Descriptor.Value, out this._parameters, out this._returnType);
        }

        public MethodInfo TargetMethod
        {
            get
            {
                if (this._targetMethod == null)
                {
                    var targetCls = JVMClassLoader.LoadClass(this.ClassInfo.TypeInfo.Name);
                    this._targetMethod = targetCls.Methods.First(
                        m => m.Name.Value == this.NameAndKeyInfo.Name.Value &&
                            m.IsMethodDefineEquals(this)
                        );
                }
                return this._targetMethod;
            }
        }
        public ConstantMethodRefInfo(BinaryReader reader, JavaClass cls)
            : base(reader, cls)
        {

        }

    }
}
